package com.ipay.wechat.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.ipay.annotation.IgnoreAuth;
import com.ipay.common.Base64Coder;
import com.ipay.entity.BizSequenceType;
import com.ipay.foreign.pojo.MerchantPayParameter;
import com.ipay.foreign.service.MerchantPayParameterService;
import com.ipay.service.impl.DefaultSequenceManager;
import com.ipay.utils.MD5;
import com.ipay.utils.MapUtils;
import com.ipay.utils.R;
import com.ipay.utils.StringUtil;
import com.ipay.wechat.pojo.PayorderEntity;
import com.ipay.wechat.pojo.QRCode;
import com.ipay.wechat.service.QRCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ipay.wechat.component.Wechat;
import com.ipay.wechat.factory.AuthorizeFactory;
import com.ipay.wechat.pojo.MerchantInfoEntity;
import com.ipay.wechat.service.MerchantInfoService;

/**
 * 授权
 *
 * @author Administrator
 */
@Controller
public class AuthorizeController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private AuthorizeFactory auFatory;
    @Autowired
    private Wechat wechat;
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private QRCodeService codeService;
    @Autowired
    private MerchantPayParameterService merchantPayParameterService;

    @ResponseBody
    @RequestMapping(value = "/menu", method = RequestMethod.GET)
    public ModelAndView authorizeLogin(@RequestParam String action) {
        logger.info("==/menu===:" + action);
        String post_url = auFatory.dealAuthorize(action, null);
        return new ModelAndView("redirect:" + post_url);
    }

    /////////////////////////////////公众号支付///////////////////////////////////////
    /**支付入口  第一步  获取微信或支付宝信息
     * @param merchantNo         商户号
     * @param codeNo             收款码编号
     * @param request
     * @param redirectAttributes
     * @return https://www.***.cn/wechat/merchant/userAgent?merchantNo=D2017103112000000012
     */
    @RequestMapping(value = "/merchant/userAgent", method = RequestMethod.GET)
    public ModelAndView getUserAgent(@RequestParam String merchantNo, @RequestParam String codeNo, HttpServletRequest request,
                                     final RedirectAttributes redirectAttributes) {
        String params = "?merchantNo=" + merchantNo + "&codeNo=" + codeNo;
        String ua = request.getHeader("User-Agent");
        String post_url = "";
        if (ua.indexOf("MicroMessenger") > 0) {// 微信
            post_url = auFatory.dealAuthorize("userAgent", params);
        } else if (ua.indexOf("AlipayClient") > 0) {// 支付宝
            post_url = auFatory.createAliPostUrl(params);
        }
        logger.debug("post_url------------" + post_url);
        return new ModelAndView("redirect:" + post_url);
    }
    /**
     * 支付入口  第二步
     * @param merchantNo         商户号
     * @param codeNo             收款码编号
     * @param request
     * @param redirectAttributes
     * @return
     * @throws UnsupportedEncodingException https://www.***.cn/wechat/merchant/userAgent?merchantNo=D2017103112000000012
     */
    @RequestMapping(value = "/auth/userAgent", method = RequestMethod.GET)
    public ModelAndView authRedirect(@RequestParam String merchantNo, @RequestParam String codeNo, HttpServletRequest request,
                                     final RedirectAttributes redirectAttributes) throws UnsupportedEncodingException {
        String ua = request.getHeader("User-Agent");
        if (ua.indexOf("MicroMessenger") > 0) {
            // 微信
            redirectAttributes.addAttribute("User-Agent", "MicroMessenger");
        } else if (ua.indexOf("AlipayClient") > 0) {
            // 支付宝
            redirectAttributes.addAttribute("User-Agent", "AlipayClient");
        }
        logger.debug("merchantNo-----" + merchantNo);
        logger.debug("baseUrl-----" + wechat.getBaseUrl());
        redirectAttributes.addAttribute("codeNo", codeNo);
        redirectAttributes.addAttribute("merchantId", merchantNo);
        redirectAttributes.addAttribute("openid", request.getSession().getAttribute("openid"));
        //TODO 已确认可以这样处理
        MerchantInfoEntity merchantInfo = merchantInfoService.queryObject(merchantNo);
        request.setCharacterEncoding("utf-8");
        if (merchantInfo != null) {
            String shopName = java.net.URLEncoder.encode(merchantInfo.getShopName(), "utf-8");
            String logo = merchantInfo.getLogo();
            logger.info("shopName-------------" + merchantInfo.getShopName());
            logger.info("logo-------------" + merchantInfo.getLogo());
            redirectAttributes.addAttribute("logo", logo);
            redirectAttributes.addAttribute("shopName", shopName);
            redirectAttributes.addAttribute("baseUrl", wechat.getBaseUrl());
            redirectAttributes.addAttribute("baseUrlWechat", wechat.getBaseUrlWechat());
            //return new ModelAndView("redirect:" +wechat.getBaseUrl()+"pay/payment.html");
            return new ModelAndView("redirect:" + wechat.getBaseUrlWechat() + "payment.html");
        }
        //TODO 如删除pay文件夹里的内容记得修改
        return new ModelAndView("pay/payError.jsp").addObject("errorMesage", "支付参数错误");
    }


    ///////////////////////////////////////收款员  固定金额支付////////////////////////////////////////
    /**
     * @param payId              支付参数Id
     * @param codeNo             收款码编号
     * @param request
     * @param redirectAttributes
     * @return https://www.***.cn/wechat/merchant/userAgent?merchantNo=D2017103112000000012
     */
    @RequestMapping(value = "/merchant/payFMGateway", method = RequestMethod.GET)
    public ModelAndView payFMGateway(@RequestParam String payId, @RequestParam String codeNo, HttpServletRequest request,
                                     final RedirectAttributes redirectAttributes) {
        logger.info("*************payFMGateway=====payId:"+payId+"  =  codeNo:"+codeNo);
        ///根据payId查询固定金额支付相关参数
        MerchantPayParameter merchantPay = merchantPayParameterService.queryObject(payId);
        if (merchantPay != null && StringUtil.isNotEmpty(merchantPay.getMerchantNo())) { //商户编号不能为空
            if (StringUtil.isNotEmpty(merchantPay.getCodeNo()) && codeNo.equals(merchantPay.getCodeNo())) { ///支付  收款员编号与查询的参数里的收款员编号是否相符
                String params = "?payId=" + payId + "&codeNo=" + codeNo + "&merchantNo=" + merchantPay.getMerchantNo();
                String ua = request.getHeader("User-Agent");
                String post_url = "";
                if (ua.indexOf("MicroMessenger") > 0) {
                    // 微信
                    post_url = auFatory.dealAuthorize("payFMGateway", params);
                } else if (ua.indexOf("AlipayClient") > 0) {
                    // 支付宝
                    post_url = auFatory.createAliPostUrl("payFMGateway", params);
                }
                logger.debug("payFMGateway---post_url------------" + post_url);
                return new ModelAndView("redirect:" + post_url);
            }
        }
        return new ModelAndView("pay/payError.jsp").addObject("errorMesage", "支付参数错误");
    }

    /**
     * 固定金额 用户 金额确定页面  进入入口
     * @param payId              支付参数Id
     * @param codeNo             收款码编号
     * @param request
     * @param redirectAttributes
     * @return
     * @throws UnsupportedEncodingException https://www.***.cn/wechat/merchant/userAgent?merchantNo=D2017103112000000012
     */
    @RequestMapping(value = "/auth/payFMGateway", method = RequestMethod.GET)
    public ModelAndView authFMRedirect(@RequestParam String payId, @RequestParam String codeNo, @RequestParam String merchantNo, HttpServletRequest request,
                                       final RedirectAttributes redirectAttributes) throws UnsupportedEncodingException {
        ///根据payId查询固定金额支付相关参数
        MerchantPayParameter merchantPay = merchantPayParameterService.queryObject(payId);
        if (merchantPay != null && StringUtil.isNotEmpty(merchantPay.getMerchantNo())) { //商户编号不能为空
            if (StringUtil.isNotEmpty(merchantPay.getCodeNo()) && codeNo.equals(merchantPay.getCodeNo())) { ///支付  收款员编号与查询的参数里的收款员编号是否相符
                String ua = request.getHeader("User-Agent");
                if (ua.indexOf("MicroMessenger") > 0) {// 微信
                    redirectAttributes.addAttribute("User-Agent", "MicroMessenger");
                } else if (ua.indexOf("AlipayClient") > 0) {// 支付宝
                    redirectAttributes.addAttribute("User-Agent", "AlipayClient");
                }
                logger.debug("payFMGateway---baseUrl-----" + wechat.getBaseUrl() + "===payId:" + payId);
                redirectAttributes.addAttribute("payId", payId);
                redirectAttributes.addAttribute("codeNo", codeNo);
                redirectAttributes.addAttribute("merchantId", merchantNo);
                redirectAttributes.addAttribute("payMoney", merchantPay.getPayMoney());
                redirectAttributes.addAttribute("openid", request.getSession().getAttribute("openid"));
                //TODO 确认可以这样处理
                MerchantInfoEntity merchantInfo = merchantInfoService.queryObject(merchantNo);
                request.setCharacterEncoding("utf-8");
                if (merchantInfo != null) {
                    String shopName = java.net.URLEncoder.encode(merchantInfo.getShopName(), "utf-8");
                    String logo = merchantInfo.getLogo();
                    redirectAttributes.addAttribute("logo", logo);
                    redirectAttributes.addAttribute("shopName", shopName);
                    redirectAttributes.addAttribute("baseUrl", wechat.getBaseUrl());
                    redirectAttributes.addAttribute("baseUrlWechat", wechat.getBaseUrlWechat());
                    return new ModelAndView("redirect:" + wechat.getBaseUrlWechat() + "payFMment.html");
                }
            }
        }
        //TODO 如删除pay文件夹里的内容记得修改
        return new ModelAndView("pay/payError.jsp").addObject("errorMesage", "支付参数错误");
    }


    public ModelAndView authAliOpenid(@RequestParam String merchantNo, HttpServletRequest request,
                                      final RedirectAttributes redirectAttributes) {
        String params = "?merchantNo=" + merchantNo;
        String post_url = auFatory.createAliPostUrl(params);
        return new ModelAndView("redirect:" + post_url);
    }

}